package com.benmei.weike.service;

import com.benmei.weike.common.Constants;
import com.benmei.weike.common.GoodsCategory;
import com.benmei.weike.common.PayType;
import com.benmei.weike.common.PaymentConstants;
import com.benmei.weike.dao.*;
import com.benmei.weike.dto.*;
import com.benmei.weike.dto.weikeContentResponse.*;
import com.benmei.weike.dto.weikeDetailResponse.Part;
import com.benmei.weike.dto.weikeDetailResponse.WeikeDetailResponse;
import com.benmei.weike.entity.*;
import com.benmei.weike.exception.ClientException;
import com.benmei.weike.exception.ServerException;
import com.benmei.weike.util.AliyunOssUtil;
import com.benmei.weike.util.DateUtil;
import com.benmei.weike.util.OrderUtil;
import com.benmei.weike.web.WeikeTeacherController;
import com.nativetalk.bean.member.TdNtMembFoundChange;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.teacher.TdNtTeaFoundChange;
import com.nativetalk.bean.teacher.TdNtTeacherLabel;
import com.nativetalk.bean.teacher.TdNtTeacherResult;
import com.nativetalk.bean.teacher.TeacherLabel;
import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.*;
import com.pingplusplus.model.Charge;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

@Service
public class WeikeService {

    public static final Logger logger = LoggerFactory.getLogger(WeikeTeacherController.class);
    public static final String WAIJIAOJUN_WEIKE_CONTENT = "waijiaojun/weike/content/";
    public static final String WAIJIAOJUN_Teacher = "waijiaojun/app/teacher/";


    @Value("${Ping++.APP_ID}")
    public String pingAppId;
    @Value("${Ping++.Secret_Key}")
    public String pingSecretKey;
    @Value("${Ping++.Test}")
    public String pingTest;
    @Value("${weikeShareUrlPrefix}")
    public String weikeShareUrlPrefix;

    @Resource
    private WeikeDao weikeDao;

    @Resource
    private WeikePartDao weikePartDao;

    @Resource
    private WeikeContentDao weikeContentDao;

    @Resource
    private WeikeImageDao weikeImageDao;

    @Resource
    private WeikeStudentBuyDao weikeStudentBuyDao;

    @Resource
    private TdNtTeacherDao tdNtTeacherDao;

    @Resource
    private WeikeCommentsDao weikeCommentsDao;

    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;

    @Resource
    private TdNtMemberDao tdNtMemberDao;

    @Resource
    private TdNtTeaFoundChangeDao tdNtTeaFoundChangeDao;

    @Resource
    private WeikeStudentPlayedAudioDao weikeStudentPlayedAudioDao;

    @Resource
    private WeikeSubscriptionDao weikeSubscriptionDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private CompositeCourseDao compositeCourseDao;

    @Autowired
    private MemberSalesPromotionDao memberSalesPromotionDao;

    @Autowired
    private MemberSalesPromotionSettingsDao memberSalesPromotionSettingsDao;

    @Autowired
    private WeikeSubscriptionDescDao weikeSubscriptionDescDao;

    @Autowired
    private WeikeStudentStudyPartDao weikeStudentStudyPartDao;

    @Autowired
    private WeikeTeacherHourChargeDao weikeTeacherHourChargeDao;

    @Resource
    private SystemConfigDao systemConfigDao;

    @Resource
    private TeacherDao teacherDao;
    @Resource
    private DictDao dictDao;
    @Resource
    private WebsiteConfigDao websiteConfigDao;

    public int insert(Weike pojo) {
        return weikeDao.insert(pojo);
    }

    public int insertSelective(Weike pojo) {
        return weikeDao.insertSelective(pojo);
    }

    public int insertList(List<Weike> pojos) {
        return weikeDao.insertList(pojos);
    }

    public int update(Weike pojo) {
        return weikeDao.update(pojo);
    }

    public boolean isPublished(Long weikeId) {
        boolean isPublished = false;
        Weike weike = weikeDao.getById(weikeId);
        if (weike != null) {
            int weikePublished = weike.getPublished() == null ? -1 : weike.getPublished();
            if (Constants.Weike.Published.YES.intValue() == weikePublished) {
                isPublished = true;
            }
        }
        return isPublished;
    }

    /**
     * 查询老师个人的微课列表
     *
     * @param req
     * @param tea_id
     * @return
     * @throws ClientException
     */
    public TeacherWeikeListResponse teacherWeikeList(TeacherWeikeListRequest req, Integer tea_id) throws ClientException {
        TeacherWeikeListResponse pageResponse = new TeacherWeikeListResponse(req.getPageSize(), req.getCurrentPage());

        Weike weike = new Weike();
        weike.setDeleted(Constants.Deleted.NO);
        weike.setPublish_user_id(tea_id);

        //第1个tab 查询审核通过的微课,并且是已发布的
        List<Weike> list;
        RowBounds rowBounds = new RowBounds(pageResponse.getOffset().intValue(), pageResponse.getPageSize().intValue());
        if (TeacherWeikeListRequest.Status.page1.intValue() == req.getStatus().intValue()) {
            weike.setApproved(Constants.Weike.Approved.PASS);
            weike.setPublished(Constants.Weike.Published.YES);
            weike.setDeleted(Constants.Deleted.NO);
            Long total = weikeDao.searchWeikeCount(weike);
            pageResponse.setTotal(total);
            list = weikeDao.searchWeike(weike, rowBounds);

        }//第2个tab 查询审核通过的微课,并且是未发布的
        else if (TeacherWeikeListRequest.Status.page2.intValue() == req.getStatus().intValue()) {
            weike.setApproved(Constants.Weike.Approved.PASS);
            weike.setPublished(Constants.Weike.Published.NO);
            weike.setDeleted(Constants.Deleted.NO);
            Long total = weikeDao.searchWeikeCount(weike);
            pageResponse.setTotal(total);
            list = weikeDao.searchWeike(weike, rowBounds);

        }//第3个tab 查询审核不通过和未审核的微课（即：!通过）
        else if (TeacherWeikeListRequest.Status.page3.intValue() == req.getStatus().intValue()) {
            weike.setApproved(Constants.Weike.Approved.PASS);
            weike.setDeleted(Constants.Deleted.NO);
            Long total = weikeDao.searchWeikeForPendingCount(weike);
            pageResponse.setTotal(total);
            list = weikeDao.searchWeikeForPending(weike, rowBounds);//searchWeikeForPending 中的sql对approved做 != 操作

        } else {
            logger.error("Invalid Status:" + req.getStatus());
            throw new ClientException("Invalid Status:" + req.getStatus());
        }
        pageResponse.setData(list);
        return pageResponse;
    }

    @Transactional
    public Weike teacherCreateWeike(TeacherWeikeCreateRequest req, Integer tea_id) {
        Weike weike = new Weike();
        Date now = new Date();
        weike.setCreate_user(tea_id);
        weike.setCreate_date(now);
        weike.setUpdate_user(tea_id);
        weike.setUpdate_date(now);
        weike.setDeleted(Constants.Deleted.NO);

        weike.setTitle(req.getTitle());
        weike.setIntro(req.getIntro());
        weike.setApproved(Constants.Weike.Approved.NONE);
        weike.setPublished(Constants.Weike.Published.NO);
        weike.setHot(Constants.Weike.Hot.NO);

        weike.setBoutique(Constants.Weike.Boutique.NO);
        weike.setToday_boutique(Constants.Weike.TodayBoutique.NO);
        weike.setBuy_number(0);//购买人数
        weike.setStudy_number(0);
        weike.setScore(Constants.Weike.default_score);//评分
        weike.setShow_on_student(Constants.Weike.Show.YES);

        weike.setStudent_price(Constants.Weike.default_student_price);
        weike.setTeacher_earn(Constants.Weike.default_teacher_earn_price);
        weike.setPublish_user_id(tea_id);
        weike.setCategory_id(Constants.Weike.default_category_id);

        weike.setCover_url(uploadCoverToOss(req.getCover()));   //上传微课封面图片到OSS
        weike.setApproved(-1);    //保存微课内容

        weikeDao.insertSelective(weike);
        return weike;
    }

    /**
     * 老师更新微课
     *
     * @param req
     * @param tea_id
     * @return
     * @throws ClientException
     */
    @Transactional
    public Weike teacherUpdateWeike(TeacherWeikeCreateRequest req, Integer tea_id) throws ClientException {
        Weike weike = weikeDao.getById(req.getId());
        if (StringUtils.isBlank(weike.getCover_url()) && req.getCover() == null) {
            throw new ClientException("Parameter 'cover' is required");
        }
        if (StringUtils.isBlank(weike.getCover_url()) && req.getCover().getSize() == 0) {
            throw new ClientException("The cover size can't be 0");
        }

        weike.setApproved(Constants.Weike.Approved.NONE);
        weike.setTitle(req.getTitle());
        weike.setIntro(req.getIntro());
        weike.setUpdate_date(new Date());
        weike.setUpdate_user(tea_id);

        if (req.getCover() != null) {
            weike.setCover_url(uploadCoverToOss(req.getCover()));   //上传微课封面图片到OSS
        }

        weikeDao.update(weike);
        return weike;
    }

    /**
     * 上传图片到阿里云
     *
     * @param cover
     */
    private String uploadCoverToOss(MultipartFile cover) {
        try {
            String oss_pathname = AliyunOssUtil.uploadWeikeCover(cover);
            return oss_pathname;
        } catch (Exception e) {
            String msg = "File upload to OSS error.[" + cover.getOriginalFilename() + "]";
            logger.error(msg, e);
            throw new ServerException(msg);
        }
    }

    /**
     * 添加文字
     *
     * @param type
     * @param weike_id
     * @param weike_part_sort
     * @param text
     * @return
     */
    @Transactional
    public WeikeContent teacherAddText(String type, String weike_id, String weike_part_sort, String text, Integer create_user) {
        WeikeContent weikeContent = new WeikeContent();
        weikeContent.setCreate_user(create_user);
        weikeContent.setWeike_id(Long.valueOf(weike_id));
        weikeContent.setWeike_part_sort(Integer.valueOf(weike_part_sort));
        weikeContent.setType(type);
        weikeContent.setContent(text);
        weikeContent.setDeleted(0);
        Integer sort = weikeContentDao.searchSortCount(Long.valueOf(weike_id), Integer.valueOf(weike_part_sort));
        weikeContent.setSort(sort + 1);
        weikeContentDao.insertSelective(weikeContent);
        return weikeContent;
    }

    /**
     * 修改微课文本内容
     *
     * @param id
     * @param text
     * @param update_user
     * @return
     */
    public WeikeContent teacherUpdateText(String id, String text, String type, Integer update_user) {
        WeikeContent weikeContent = new WeikeContent();
        weikeContent.setId(Long.valueOf(id));
        weikeContent.setContent(text);
        weikeContent.setType(type);
        weikeContent.setUpdate_user(update_user);
        weikeContentDao.update(weikeContent);
        return weikeContent;
    }

    /**
     * 添加音频
     *
     * @param type
     * @param weike_id
     * @param weike_part_sort
     * @param audio
     * @param duration
     * @return
     */
    @Transactional
    public WeikeContent teacherAddAudio(String type, String weike_id, String weike_part_sort, MultipartFile audio, String duration, Integer create_user) {
        WeikeContent weikeContent = new WeikeContent();
        weikeContent.setWeike_id(Long.valueOf(weike_id));
        weikeContent.setType(type);
        weikeContent.setCreate_user(create_user);
        weikeContent.setWeike_part_sort(Integer.valueOf(weike_part_sort));
        weikeContent.setDuration(Long.valueOf(duration));
        weikeContent.setDeleted(0);
        //上传语音到OSS
        try {
            String oname = audio.getOriginalFilename();
            String newName = AliyunOssUtil.getRandomFileName(oname);
            String key = WAIJIAOJUN_WEIKE_CONTENT + weike_id + "/" + newName;
            AliyunOssUtil.upload(key, audio.getInputStream(), audio.getSize());
            weikeContent.setContent(key);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        Integer sort = weikeContentDao.searchSortCount(Long.valueOf(weike_id), Integer.valueOf(weike_part_sort));
        weikeContent.setSort(sort + 1);
        weikeContentDao.insertSelective(weikeContent);
        return weikeContent;
    }

    /**
     * 修改音频
     *
     * @param id
     * @param type
     * @param audio
     * @param duration
     * @param update_user
     * @return
     */
    public WeikeContent teacherUpdateAudio(String id, String weike_id, String type, MultipartFile audio, String duration, Integer update_user) {
        WeikeContent weikeContent = new WeikeContent();
        weikeContent.setId(Long.valueOf(id));
        weikeContent.setType(type);
        weikeContent.setWeike_id(Long.valueOf(weike_id));
        weikeContent.setDuration(Long.valueOf(duration));
        weikeContent.setUpdate_user(update_user);
        //上传语音到OSS
        try {
            String oname = audio.getOriginalFilename();
            String newName = AliyunOssUtil.getRandomFileName(oname);
            String key = WAIJIAOJUN_WEIKE_CONTENT + weike_id + "/" + audio + "_" + newName;
            AliyunOssUtil.upload(key, audio.getInputStream(), audio.getSize());
            weikeContent.setContent(key);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        weikeContentDao.update(weikeContent);
        return weikeContent;
    }

    /**
     * 删除微课内容
     *
     * @param id
     * @param update_user
     * @return
     */
    public String teacherDeletePartContent(String id, Integer update_user) {
        WeikeContent weikeContent = new WeikeContent();
        weikeContent.setId(Long.valueOf(id));
        weikeContent.setUpdate_user(update_user);
        weikeContent.setDeleted(1);
        weikeContentDao.update(weikeContent);
        return "微课章节内容删除成功";
    }

    /**
     * 上传PPT
     *
     * @param weike_id
     * @param weike_part_sort
     * @param create_user
     * @param files
     * @return
     */
    public List<WeikeImage> uploadImage(String weike_id, String weike_part_sort, Integer create_user, List<MultipartFile> files) {
        List<WeikeImage> weikeImageList = new ArrayList<WeikeImage>();
        Integer sort = weikeImageDao.searchPartCount(Long.valueOf(weike_id), Integer.valueOf(weike_part_sort));
        for (int i = 0; i < files.size(); i++) {
            MultipartFile image = files.get(i);
            WeikeImage weikeImage = new WeikeImage();
            weikeImage.setWeike_id(Long.valueOf(weike_id));
            weikeImage.setWeike_part_sort(Integer.valueOf(weike_part_sort));
            weikeImage.setCreate_user(create_user);
            weikeImage.setUpdate_user(create_user);
            weikeImage.setDeleted(0);
            weikeImage.setSort(sort + 1 + i);
            //上传图片到OSS
            try {
                String oname = image.getOriginalFilename();
                String newName = AliyunOssUtil.getRandomFileName(oname);
                String key = WAIJIAOJUN_WEIKE_CONTENT + weike_id + "/" + weike_part_sort + "_" + newName;
                AliyunOssUtil.upload(key, image.getInputStream(), image.getSize());
                weikeImage.setUrl(key);
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
            weikeImageList.add(weikeImage);
        }
        weikeImageDao.insertList(weikeImageList);
        return weikeImageList;
    }

    /**
     * 删除PPT图片
     *
     * @param id
     * @param update_user
     * @return
     */
    public WeikeImage deleteImage(String id, Integer update_user) {
        WeikeImage weikeImage = new WeikeImage();
        weikeImage.setId(Long.valueOf(id));
        weikeImage.setDeleted(1);
        weikeImage.setUpdate_user(update_user);
        weikeImageDao.update(weikeImage);
        return weikeImage;
    }

    /**
     * 根据URL删除PPT图片
     *
     * @param url
     * @param update_user
     * @return
     */
    public WeikeImage deleteImageByUrl(String url, Integer update_user) {
        WeikeImage weikeImage = new WeikeImage();
        weikeImage.setUrl(url);
        weikeImage.setDeleted(1);
        weikeImage.setUpdate_user(update_user);
        weikeImageDao.deleteByUrl(url, update_user);
        return weikeImage;
    }

    /**
     * 移动图片位置
     *
     * @param id
     * @param oldSort
     * @param sort
     * @param update_user
     * @return
     */
    public String moveImageSort(String id, String oldSort, String sort, Integer update_user) {
        Long imgId = Long.parseLong(id);
        Integer newSort = Integer.parseInt(sort);
        Integer oSort = Integer.parseInt(oldSort);
        WeikeImage image = new WeikeImage();
        image.setId(imgId);
        image.setSort(newSort);
        if (newSort > oSort) {
            weikeImageDao.updateLater(imgId, oSort, newSort);
        } else if (newSort < oSort) {
            weikeImageDao.updateForword(imgId, newSort, oSort);
        } else {
        }
        weikeImageDao.update(image);
        return "移动成功";
    }

    /**
     * 保存微课内容：ppt,parts,texts,audios
     *
     * @param parts
     * @param pictures
     * @param contents
     */
    @Transactional(readOnly = false)
    public void saveContents(Long weikeId, List<WeikePart> parts, List<WeikeImage> pictures, List<WeikeContent> contents, Integer teaId) throws ClientException, Exception {
        //上传图片到OSS
        try {
            for (WeikeImage image : pictures) {
                MultipartFile file = image.getFile();
                String oname = file.getOriginalFilename();
                String newName = AliyunOssUtil.getRandomFileName(oname);
                String key = WAIJIAOJUN_WEIKE_CONTENT + image.getWeike_id() + "/" + image.getClientFieldName() + "_" + newName;
                AliyunOssUtil.upload(key, file.getInputStream(), file.getSize());
                image.setUrl(key);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }

        //上传语音到OSS
        try {
            for (WeikeContent content : contents) {
                if (Constants.Weike.CtxType.AUDIO.equals(content.getType())) {
                    MultipartFile file = content.getFile();
                    String oname = file.getOriginalFilename();
                    String newName = AliyunOssUtil.getRandomFileName(oname);
                    String key = WAIJIAOJUN_WEIKE_CONTENT + content.getWeike_id() + "/" + content.getClientFieldName() + "_" + newName;
                    AliyunOssUtil.upload(key, file.getInputStream(), file.getSize());
                    content.setContent(key);//设置语音url
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }

        weikePartDao.insertList(parts);

        if (pictures != null && pictures.size() > 0) {
            weikeImageDao.insertList(pictures);
        }
        weikeContentDao.insertList(contents);

        //修改微课状态为已发布
        Weike weike = new Weike();
        weike.setId(weikeId);
        weike.setPublished(Constants.Weike.Published.YES);
        weikeDao.update(weike);

        //给老师加20美元
        teacherChargeForWeike(teaId);

        // MQ 发布消息
        rabbitTemplate.convertAndSend("teenager-weike-published", weike);
    }

    private void teacherChargeForWeike(Integer teaId) {
        // 资金变化记录
        BigDecimal balance = tdNtTeacherDao.findTdNtTeacherBalance(teaId);   // 查询老师账户余额（)
        TdNtTeaFoundChange teaFoundChange = new TdNtTeaFoundChange();
        teaFoundChange.setTea_id(teaId);
        teaFoundChange.setState(Constants.PayState.success);
        teaFoundChange.setTfchg_front_amount(balance);
        BigDecimal earned = new BigDecimal(20);  //一门微课赚20美元
        teaFoundChange.setTfchg_back_amount(balance.add(earned));  //设置变化后的金额
        teaFoundChange.setTfchg_change_amount(earned);
        Date now = new Date();
        Timestamp now2 = new Timestamp(now.getTime());
        teaFoundChange.setTfchg_change_month(DateUtil.getMonth(now));
        teaFoundChange.setTfchg_change_time(now2);
        teaFoundChange.setTfchg_change_type(Constants.FundFlowType.in);//
        teaFoundChange.setTfchg_account(new BigDecimal(0.00d));//暂时不设置，看看有什么影响，感觉没用处。
        teaFoundChange.setTfchg_counter_fee(new BigDecimal(0.00d));//暂时不设置，看看有什么影响，感觉没用处。 费用，手续费
        teaFoundChange.setTfchg_number(OrderUtil.getOrderNumber());//订单号
        teaFoundChange.setType(Constants.fundChangeTypeForTeacher.weike_code);
        teaFoundChange.setTfchg_change_name(Constants.fundChangeTypeForTeacher.weike_msg);
        tdNtTeaFoundChangeDao.insert(teaFoundChange);

        // 更新老师余额
        tdNtTeacherDao.addBalance(teaId, earned);
        logger.info(" ---------- 计费 end -----------");

    }

    /**
     * <pre>
     * {
     * "images":[
     * {"sort":1,"part":1,"url":"xxx/xxx.jpg"}
     * ],
     * "parts":[{
     * "sort":1,
     * "title":"段落标题",
     * "contents":[
     * {"id":1,"sort":1,"type":"audio","content":"xxx/sss.wav","duration":320,"play_number":0},
     * {"id":2,"sort":2,"type":"text","content":"This content very good.","duration":0,"play_number":0 }
     * ]
     * }]
     * }
     * </pre>
     * 学生端查询微课内容
     *
     * @param memb_id
     * @param weikeId
     */
    public StudentWeikeContentRespons getWeikeContent(Integer memb_id, Long weikeId) {
        StudentWeikeContentRespons response = new StudentWeikeContentRespons();

        Weike weike = weikeDao.getById(weikeId);
        if (weike == null) {
            logger.error("学生或网页端查询微课详情，微课id不存在，weikeId=" + weikeId);
            return response;
        }
        response.setWeike_video(weike.getWeike_video());
        response.setWeike_video_img(weike.getWeike_video_img());
        response.setPrice(weike.getStudent_price());
        response.setWeike_id(weikeId);
        //查询老师信息
        Integer tea_id = weike.getCreate_user();
        TdNtTeacherResult teacher = tdNtTeacherDao.getById(tea_id);
        if (teacher != null) {
            response.setTeacher_avatar_url(teacher.getTea_head_portrait());
        }

        //查询微课内容
        List<WeikeImage> weikeImages = weikeImageDao.searchByWeikeId(weikeId);
        if (weikeImages == null) {
            weikeImages = new ArrayList<>();
        }
        List<WeikePart> weikeParts = weikePartDao.searchByWeikeId(weikeId);
        if (weikeParts == null) {
            weikeParts = new ArrayList<>();
        }
        List<WeikeContent> weikeContents = null;
        if (memb_id != null) {
            weikeContents = weikeContentDao.searchByWeikeIdWithPlayNumber(weikeId, memb_id);
        } else {
            weikeContents = weikeContentDao.searchByWeikeId(weikeId);
        }

        if (weikeContents == null) {
            weikeContents = new ArrayList<>();
        }

        for (WeikeImage image : weikeImages) {
            WeikeImageDto imageDto = new WeikeImageDto(image.getId(), image.getSort(), image.getWeike_part_sort(), image.getUrl());
            response.images.add(imageDto);
        }
        //Collections.sort(response.images);
        for (WeikePart part : weikeParts) {
            WeikePartDto partDto = new WeikePartDto(part.getId(), part.getSort(), part.getTitle());
            for (WeikeContent ctx : weikeContents) {
                if (ctx.getWeike_part_sort().intValue() == part.getSort().intValue()) {
                    WeikeContentDto ctxDto = new WeikeContentDto();
                    ctxDto.setDuration(ctx.getDuration());
                    ctxDto.setSort(ctx.getSort());
                    ctxDto.setContent(ctx.getContent());
                    ctxDto.setId(ctx.getId());
                    ctxDto.setType(ctx.getType());
                    ctxDto.setPart_sort(part.getSort());

                    ctxDto.setPlay_number(ctx.getPlay_number());//播放次数
                    partDto.contents.add(ctxDto);
                }
            }
            Collections.sort(partDto.contents);
            response.parts.add(partDto);
        }

        Collections.sort(response.parts);

        if (memb_id != null) {
            //查询该学生是否购买过该微课
            response.setBought(isBuys(memb_id, weikeId));

            //查询该学生对该微课的评价分数
            Integer studentScore = 0;
            WeikeComments comments = new WeikeComments();
            comments.setMemb_id(memb_id);
            comments.setWeike_id(weikeId);
            List<WeikeComments> list = weikeCommentsDao.find(comments);
            if (list != null && list.size() > 0) {
                studentScore = list.get(0).getScore() == null ? 0 : list.get(0).getScore();
            }
            response.setStudentScore(studentScore);
        }

        return response;
    }

    /**
     * 老师端查询微课详情
     *
     * @param weikeId
     * @return WeikeContentRespons
     */
    public WeikeContentResponse getWeikeContent(Long weikeId) {
        //查询微课内容
        List<WeikeImage> weikeImages = weikeImageDao.searchByWeikeIdForTeacher(weikeId);
        if (weikeImages == null) {
            weikeImages = new ArrayList<>();
        }

        List<WeikePart> weikeParts = weikePartDao.searchByWeikeIdForTeacher(weikeId);
        if (weikeParts == null) {
            weikeParts = new ArrayList<>();
        }
        List<WeikeContent> weikeContents = weikeContentDao.searchByWeikeIdForTeacher(weikeId);
        if (weikeContents == null) {
            weikeContents = new ArrayList<>();
        }

        WeikeContentResponse weikeContentRespons = new WeikeContentResponse();
        for (WeikeImage image : weikeImages) {
            WeikeImageDto imageDto = new WeikeImageDto(image.getId(), image.getSort(), image.getWeike_part_sort(), image.getUrl());
            weikeContentRespons.images.add(imageDto);
        }

        for (WeikePart part : weikeParts) {
            WeikePartDto partDto = new WeikePartDto(part.getId(), part.getSort(), part.getTitle());
            for (WeikeContent ctx : weikeContents) {
                if (ctx.getWeike_part_sort().intValue() == part.getSort().intValue()) {
                    WeikeContentDto ctxDto = new WeikeContentDto();
                    ctxDto.setDuration(ctx.getDuration());
                    ctxDto.setSort(ctx.getSort());
                    ctxDto.setContent(ctx.getContent());
                    ctxDto.setId(ctx.getId());
                    ctxDto.setType(ctx.getType());
                    ctxDto.setPart_sort(part.getSort());
                    partDto.contents.add(ctxDto);
                }
            }
            Collections.sort(partDto.contents);
            weikeContentRespons.parts.add(partDto);
        }

        Collections.sort(weikeContentRespons.parts);

        return weikeContentRespons;
    }

    /**
     * 查询精品微课
     *
     * @param pageRequest
     * @return
     */
    public PageResponse weikeBoutiqueList(PageRequest pageRequest) {

        PageResponse pageResponse = new PageResponse(pageRequest.getPageSize(), pageRequest.getCurrentPage());

        Long total = weikeDao.searchWeikeBoutiqueListCount();
        pageResponse.setTotal(total);

        RowBounds rowBounds = new RowBounds(pageResponse.getOffset().intValue(), pageResponse.getPageSize().intValue());
        List<WeikeBoutiqueListDto> list = weikeDao.searchWeikeBoutiqueList(rowBounds);

        pageResponse.setData(list);


        return pageResponse;
    }

    /**
     * 查询最热微课list
     *
     * @param pageRequest
     * @return
     */
    public PageResponse weikeHotList(PageRequest pageRequest,Integer memb_id) {
        PageResponse pageResponse = new PageResponse(pageRequest.getPageSize(), pageRequest.getCurrentPage());

        //创建查询条件
        Long total = weikeDao.searchWeikeHotListCount();
        pageResponse.setTotal(total);

        RowBounds rowBounds = new RowBounds(pageResponse.getOffset().intValue(), pageResponse.getPageSize().intValue());
        List<WeikeBoutiqueListDto> list = weikeDao.searchWeikeHotList(rowBounds);

        List<WeikeStudentBuy> weikeStudentBuyList = new ArrayList<>();

        if(memb_id != 0 && memb_id != null){
            WeikeSubscription weikeSubscription = weikeSubscriptionDao.findValidSubscribedByMembId(memb_id);
            for(WeikeBoutiqueListDto weikeBoutiqueListDto : list){
                WeikeStudentBuy weikeStudentBuy = new WeikeStudentBuy();
                weikeStudentBuy.setWeike_id(weikeBoutiqueListDto.getId());
                weikeStudentBuy.setMemb_id(memb_id);
                weikeStudentBuyList = weikeStudentBuyDao.find(weikeStudentBuy);
                if(weikeSubscription != null){
                    weikeBoutiqueListDto.setIs_lock(0);
                }
                if(weikeStudentBuyList.size() > 0){
                    weikeBoutiqueListDto.setIs_lock(0);
                }
            }
        }

        pageResponse.setData(list);


        return pageResponse;
    }

    /**
     * 学生端 - 查询微课详情
     *
     * @param memb_id
     * @param weike_id
     * @return
     */
    public WeikeDetailResponse getWeikeDetail(Integer memb_id, Long weike_id) {
        WeikeDetailResponse response = new WeikeDetailResponse();
        Weike weike = weikeDao.getById(weike_id);

        if (weike == null) {
            logger.error("微课id不存在，weike_id：" + weike_id);
            return response;
        }

        //1 设置微课基本信息
        response.setCover_url(weike.getCover_url_student());
        response.setDuration(1L);
        response.setId(weike.getId());
        response.setIntro(weike.getIntro_student());
        response.setScore(weike.getScore());
        response.setTitle(weike.getTitle_student());
        //设置浏览量
        response.setViewer_count(weike.getBuy_number());
        //设置购买次数
        response.setBuy_count(weike.getBuy_number());
        response.setPrice(weike.getStudent_price());
        response.setShare_url(this.weikeShareUrlPrefix + "/" + weike.getId());
        response.setIntro_video(weike.getIntro_video());
        response.setUpdate_course(weikePartDao.findUpdateLessonCount(weike_id));
        if(weike.getWeike_video() == "" || weike.getWeike_video() == null){
            response.setIs_video(0);
        }else{
            response.setIs_video(1);
        }

        //2 查询并设置老师信息
        Integer tea_id = weike.getCreate_user();
        TdNtTeacherResult teacher = tdNtTeacherDao.getById(tea_id);
        response.getTeacher().setTeacher_id(tea_id);
        response.getTeacher().setTeacher_avatar_url(teacher.getTea_head_portrait());
        response.getTeacher().setTeacher_name(teacher.getTea_name());
        int v = teacher.getTea_label();
        if (TdNtTeacherResult.Role.VIP == v) {
            response.getTeacher().setTeacher_valid(1);
        }

        //2.1 设置老师的标签
        List<TdNtTeacherLabel> labels = tdNtTeacherDao.getLabelsByTeaId(tea_id);
        for (TdNtTeacherLabel label : labels) {
            String labelName = label.getLab_en_name();
            response.getTeacher().getLabels().add(labelName);
        }

        //3. 设置Parts （查询每个Part，并且汇总每一个Part下面录音的时长， 如果memb_id=null 就不设置是否已学习字段isStudy）
        setAudioDuration(weike_id, response, memb_id);

        //7. 查询促销信息
        MemberSalesPromotion m = memberSalesPromotionDao.getForMember(memb_id);
        response.setMemberSalesPromotion(m);

        //8. 查询订阅说明
        WeikeSubscriptionDesc weikeSubscriptionDesc = weikeSubscriptionDescDao.find();
        if (weikeSubscriptionDesc != null) {
            response.setSubscriptionDesc(weikeSubscriptionDesc.getDetail());
        }

        //如果学生已经登录，那么查询学生是否对该课程进行评论和购买过，否则就默认显示未评论，未购买
        if (memb_id != null) {

            //设置该学生对这个微课的评分
            Integer myScore = 0;
            WeikeComments comments = new WeikeComments();
            comments.setWeike_id(weike_id);
            comments.setMemb_id(memb_id);
            List<WeikeComments> list = weikeCommentsDao.find(comments);
            if (list != null && list.size() > 0) {
                comments = list.get(0);
                myScore = comments.getScore();
            }
            response.setMy_score(myScore);

            //4. 查询该学生是否购买过该微课
            response.setBought(isBuys(memb_id, weike_id));

            //5. 是否评论过
            response.setCommented(isCommented(memb_id, weike_id));

            //6. 是否在订阅的有效期之内
            response.setSubscribed(isValidSubscribed(memb_id));
        }


        return response;
    }

    private Integer isValidSubscribed(Integer memb_id) {
        WeikeSubscription ws = weikeSubscriptionDao.findValidSubscribedByMembId(memb_id);
        if (ws != null) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 微课分享 - 微课详情
     *
     * @param weike_id
     * @return
     */
    public WeikeDetailResponse getWeikeDetailForSharePage(Long weike_id) {
        WeikeDetailResponse response = new WeikeDetailResponse();
        Weike weike = weikeDao.getById(weike_id);

        if (weike == null) {
            logger.error("微课id不存在，weike_id：" + weike_id);
            return response;
        }

        //1 设置微课基本信息
        response.setCover_url(weike.getCover_url_student());
        response.setDuration(1L);
        response.setId(weike.getId());
        response.setIntro(weike.getIntro_student());
        response.setScore(weike.getScore());
        response.setTitle(weike.getTitle_student());
        response.setViewer_count(weike.getBuy_number());
        response.setPrice(weike.getStudent_price());

        //2 查询并设置老师信息
        Integer tea_id = weike.getCreate_user();
        TdNtTeacherResult teacher = tdNtTeacherDao.getById(tea_id);
        response.getTeacher().setTeacher_id(tea_id);
        response.getTeacher().setTeacher_avatar_url(teacher.getTea_head_portrait());
        response.getTeacher().setTeacher_name(teacher.getTea_name());
        int v = teacher.getTea_label();
        if (TdNtTeacherResult.Role.VIP == v) {
            response.getTeacher().setTeacher_valid(1);
        }

        //2.1 设置老师的标签
        List<TdNtTeacherLabel> labels = tdNtTeacherDao.getLabelsByTeaId(tea_id);
        for (TdNtTeacherLabel label : labels) {
            String labelName = label.getLab_en_name();
            response.getTeacher().getLabels().add(labelName);
        }

        //3. 设置Parts （查询每个Part，并且汇总每一个Part下面录音的时长）
        setAudioDuration(weike_id, response, null);


        return response;
    }

    private void setAudioDuration(Long weike_id, WeikeDetailResponse response, Integer memb_id) {
        List<Part> parts = weikePartDao.findByWeikeIdWithDuration(weike_id, memb_id);

        if (parts != null) {
            response.setParts(parts);

            long duration = 0;
            for (Part p : parts) {
                duration = duration + (p.getDuration() == null ? 0L : p.getDuration());
            }
            response.setDuration(duration);
        }
    }


    /**
     * 学生memb_id 是否购买过微课weikeId
     *
     * @param memb_id
     * @param weikeId
     * @return
     */
    private Integer isBuys(Integer memb_id, Long weikeId) {
        Integer isBuy = 0;
        WeikeStudentBuy weikeStudentBuy = new WeikeStudentBuy();
        weikeStudentBuy.setDeleted(Constants.Deleted.NO);
        weikeStudentBuy.setMemb_id(memb_id);
        weikeStudentBuy.setWeike_id(weikeId);
        weikeStudentBuy.setPayment_status(WeikeStudentBuy.PaymentStatus.PAY_SUCCESS);

        List<WeikeStudentBuy> list = weikeStudentBuyDao.find(weikeStudentBuy);
        if (list != null && list.size() > 0) {
            isBuy = 1;
        }
        return isBuy;
    }

    /**
     * 学生memb_id 是否购买过微课weikeId
     *
     * @param memb_id
     * @param weikeId
     * @return
     */
    private Integer isCommented(Integer memb_id, Long weikeId) {
        Integer isCommented = 0;
        WeikeComments weikeComments = new WeikeComments();
        weikeComments.setDeleted(Constants.Deleted.NO);
        weikeComments.setMemb_id(memb_id);
        weikeComments.setWeike_id(weikeId);

        List<WeikeComments> list = weikeCommentsDao.find(weikeComments);
        if (list != null && list.size() > 0) {
            isCommented = 1;
        }
        return isCommented;
    }

    public PageResponse studentWeikeListForTeacher(StudentFindWeikeListForTeacherPageRequest req) {
        PageResponse pageResponse = new PageResponse(req.getPageSize(), req.getCurrentPage());
        Long total = weikeDao.searchByTeacherIdCount(req.getTea_id());
        pageResponse.setTotal(total);

        RowBounds rowBounds = new RowBounds(pageResponse.getOffset().intValue(), pageResponse.getPageSize().intValue());
        List<StudentFindWeikeListForTeacherDto> list = weikeDao.searchByTeacherId(req.getTea_id(), rowBounds);


        pageResponse.setData(list);
        return pageResponse;
    }


    /**
     * 学生购买微课
     *
     * @param req
     */
    public void studentPayment(StudentPaymentRequest req, Integer memb_id) throws ClientException {
        logger.info("购买微课 start");
        Weike weike = weikeDao.getById(req.getWeike_id());
        if (weike == null) {
            logger.error("微课不存在，请刷新界面后重试！");
            throw new ClientException("微课不存在，请刷新界面后重试！");
        }

        int payChannel;
        String change_name;
        if ("alipay".equals(req.getChannel())) {
            //类型为支付宝支付
            payChannel = Constants.PaymentChannel.alipay;
            change_name = "支付宝购买微课";
        } else if ("wx".equals(req.getChannel())) {
            //类型为微信支付
            payChannel = Constants.PaymentChannel.wxpay;
            change_name = "微信购买微课";
        } else {
            payChannel = Constants.PaymentChannel.wallet;
            change_name = "购买微课";
        }

        TdNtMember tdNtMember = tdNtMemberDao.getById(memb_id);
        BigDecimal balance = tdNtMember.getMemb_balance();               // 扣款前的余额
        BigDecimal price = weike.getStudent_price();     // 商品价格
        BigDecimal back_balance = new BigDecimal(0);                 // 扣款后的余额
        boolean isSufficient = balance.compareTo(price) >= 0;            // 余额是否足够支付，true余额充足，false余额不足
        boolean haveOrderNo = StringUtils.isNoneBlank(req.getOrderNo());  // 是否有订单号

        //使用余额
        if (req.getUserBlanace().intValue() == 0) {
            // 1 全部使用余额支付
            if (isSufficient) {
                back_balance = balance.subtract(price);
                logger.info("余额支付 购买微课{" + weike.getId() + ":" + weike.getTitle() + "},balance=" + balance + ", price=" + price + ", back_balance=" + back_balance + ",payChannel=" + payChannel);

                //添加资金变化记录
                addFundChange(req.getOrderNo(), memb_id, payChannel, balance, price, back_balance);
            }
            // 2 组合支付
            else {
                back_balance = new BigDecimal(0);//余额设置为0.
                logger.info("组合支付 购买微课{" + weike.getId() + ":" + weike.getTitle() + "},balance=" + balance + ", price=" + price + ", back_balance=" + back_balance + ",payChannel=" + payChannel);
                if (!haveOrderNo) {
                    logger.error("组合支付 购买微课 error:订单号为空{" + weike.getId() + ":" + weike.getTitle() + "},balance=" + balance + ", price=" + price + ", back_balance=" + back_balance + ",payChannel=" + payChannel);
                    throw new ClientException("订单号不能为空！");
                }

                //添加资金变化记录
                addFundChangeForComposite(req.getOrderNo(), memb_id, payChannel, balance, price, back_balance);
            }
        }
        // 3 不使用余额（纯第三方支付）
        else {
            /**
             * 检验订单号
             */
            if (!haveOrderNo) {
                throw new ClientException("订单号不能为空！");
            }
            back_balance = balance;
            logger.info("支付 购买微课{" + weike.getId() + ":" + weike.getTitle() + "},balance=" + balance + ", price=" + price + ", back_balance=" + back_balance + ", orderNo=" + req.getOrderNo() + ",payChannel=" + payChannel);

            //添加资金变化记录
            addFundChange(req.getOrderNo(), memb_id, payChannel, balance, price, back_balance);
        }


        //2. 更新学生余额
        tdNtMember.setMemb_balance(back_balance);
        tdNtMemberDao.updateBalance(tdNtMember);

        //3. 添加学生购买微课记录
        WeikeStudentBuy weikeStudentBuy = new WeikeStudentBuy();
        weikeStudentBuy.setPayment_status(Integer.parseInt(Constants.PayState.success));
        weikeStudentBuy.setWeike_id(weike.getId());
        weikeStudentBuy.setMemb_id(memb_id);
        weikeStudentBuy.setDeleted(Constants.Deleted.NO);
        Date date = new Date();
        weikeStudentBuy.setCreate_date(date);
        weikeStudentBuy.setCreate_user(memb_id);
        weikeStudentBuy.setStudy_number(0L);
        weikeStudentBuy.setUpdate_date(date);
        weikeStudentBuy.setUpdate_user(memb_id);
        weikeStudentBuyDao.insert(weikeStudentBuy);
        //4. 更新微课购买人数buy_number
        weike.setBuy_number(weike.getBuy_number() + 1);
        weikeDao.update(weike);

        logger.info("购买微课 end");
    }

    //组合支付添加两条记录（一条余额付款记录，一条第三方付款记录）
    private void addFundChangeForComposite(String orderNo, Integer memb_id, int payChannel, BigDecimal balance, BigDecimal price, BigDecimal back_balance) {
        boolean haveOrderNo = StringUtils.isNoneBlank(orderNo);  // 是否有订单号

        TdNtMembFoundChange tdNtMembFoundChange = tdNtMembFoundChangeDao.findTdNtMembFoundChangeByOrderNo(orderNo);
        if (tdNtMembFoundChange == null) {
            //添加 一条第三方付款记录(充值)
            BigDecimal rechargeMoney = price.subtract(balance);//充值金额
            TdNtMembFoundChange tdNtMembFoundChange2 = new TdNtMembFoundChange();
            tdNtMembFoundChange2.setMfchg_front_amount(balance);
            tdNtMembFoundChange2.setMfchg_change_amount(rechargeMoney);// 支付金额
            tdNtMembFoundChange2.setMfchg_back_amount(balance.add(rechargeMoney));
            tdNtMembFoundChange2.setMfchg_change_time(new Timestamp(new Date().getTime()));
            tdNtMembFoundChange2.setState(Constants.PayState.success);
            tdNtMembFoundChange2.setMfchg_number(orderNo);// 使用支付时生成的订单号
            tdNtMembFoundChange2.setMemb_id(memb_id);
            tdNtMembFoundChange2.setMfchg_change_month(DateUtil.getMonth(new Date()));
            tdNtMembFoundChange2.setMfchg_change_type(Constants.FundChangeType.wallet_in); //充值（进入余额：+）:1；消费（余额支出：-）:2
            tdNtMembFoundChange2.setMfchg_change_name(Constants.ChargeReason.recharge_msg);
            tdNtMembFoundChange2.setType(Constants.ChargeReason.recharge_code);//充值
            tdNtMembFoundChange2.setMoney_change_type(payChannel);
            tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChange2);

            //添加 一条余额付款记录
            tdNtMembFoundChange = new TdNtMembFoundChange();
            tdNtMembFoundChange.setMfchg_front_amount(balance);
            tdNtMembFoundChange.setMfchg_change_amount(balance);
            tdNtMembFoundChange.setMfchg_back_amount(back_balance);
            tdNtMembFoundChange.setMfchg_change_time(new Timestamp(new Date().getTime()));
            tdNtMembFoundChange.setState(Constants.PayState.success);
            tdNtMembFoundChange.setMfchg_number(OrderUtil.getOrderNumber()); // 生成一个新的订单号
            tdNtMembFoundChange.setMemb_id(memb_id);
            tdNtMembFoundChange.setMfchg_change_month(DateUtil.getMonth(new Date()));
            tdNtMembFoundChange.setMfchg_change_type(Constants.FundChangeType.wallet_out);//充值（进入余额：+）:1；消费（余额支出：-）:2
            tdNtMembFoundChange.setMfchg_change_name(Constants.ChargeReason.buy_weike_msg);
            tdNtMembFoundChange.setType(Constants.ChargeReason.buy_weike_code);
            tdNtMembFoundChange.setMoney_change_type(Constants.PaymentChannel.wallet);//余额付款
            tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChange);


        }
        // Ping++ notify 先返回，该订单的记录已插入数据库，更新业务字段
        else {
            //补全第三方支付的订单信息(充值)
            tdNtMembFoundChange.setMemb_id(memb_id);
            tdNtMembFoundChange.setMfchg_front_amount(balance);
//            tdNtMembFoundChange2.setMfchg_change_amount(price);// 支付金额
            tdNtMembFoundChange.setMfchg_back_amount(balance.add(price));

            tdNtMembFoundChange.setMfchg_change_month(DateUtil.getMonth(new Date()));
            tdNtMembFoundChange.setMfchg_change_type(Constants.FundChangeType.wallet_in);//1充值（进入余额：+）；2消费（余额支出：-）
            tdNtMembFoundChange.setMfchg_change_name(Constants.ChargeReason.recharge_msg);
            tdNtMembFoundChange.setType(Constants.ChargeReason.recharge_code);
            tdNtMembFoundChange.setMoney_change_type(payChannel);//支付渠道
            logger.info("Ping++ notify 先返回，该订单的记录已插入数据库，更新业务字段");
            tdNtMembFoundChangeDao.updatePaymentInfo(tdNtMembFoundChange);

            //添加 一条余额付款记录
            tdNtMembFoundChange = new TdNtMembFoundChange();
            tdNtMembFoundChange.setMfchg_front_amount(balance);
            tdNtMembFoundChange.setMfchg_change_amount(balance);//一条余额付款记录
            tdNtMembFoundChange.setMfchg_back_amount(back_balance);
            tdNtMembFoundChange.setMfchg_change_time(new Timestamp(new Date().getTime()));
            tdNtMembFoundChange.setState(Constants.PayState.success);
            tdNtMembFoundChange.setMfchg_number(OrderUtil.getOrderNumber());// 生成一个新的订单号
            tdNtMembFoundChange.setMemb_id(memb_id);
            tdNtMembFoundChange.setMfchg_change_month(DateUtil.getMonth(new Date()));
            tdNtMembFoundChange.setMfchg_change_type(Constants.FundChangeType.wallet_out);//充值（进入余额：+）:1；消费（余额支出：-）:2
            tdNtMembFoundChange.setMfchg_change_name(Constants.ChargeReason.buy_weike_msg);
            tdNtMembFoundChange.setType(Constants.ChargeReason.buy_weike_code);
            tdNtMembFoundChange.setMoney_change_type(Constants.PaymentChannel.wallet);//余额付款
            tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChange);
        }
    }

    private void addFundChange(String orderNo, Integer memb_id, int payChannel, BigDecimal balance, BigDecimal price, BigDecimal back_balance) {
        boolean haveOrderNo = StringUtils.isNoneBlank(orderNo);  // 是否有订单号

        TdNtMembFoundChange tdNtMembFoundChange = null;
        if (haveOrderNo) {
            tdNtMembFoundChangeDao.findTdNtMembFoundChangeByOrderNo(orderNo);
        } else {
            orderNo = OrderUtil.getOrderNumber();
        }

        if (tdNtMembFoundChange == null) {
            tdNtMembFoundChange = new TdNtMembFoundChange();

            tdNtMembFoundChange.setMfchg_front_amount(balance);
            tdNtMembFoundChange.setMfchg_change_amount(price);
            tdNtMembFoundChange.setMfchg_back_amount(back_balance);

            tdNtMembFoundChange.setMfchg_change_time(new Timestamp(new Date().getTime()));
            tdNtMembFoundChange.setState(Constants.PayState.success);
            tdNtMembFoundChange.setMfchg_number(orderNo);
            tdNtMembFoundChange.setMemb_id(memb_id);
            tdNtMembFoundChange.setMfchg_change_month(DateUtil.getMonth(new Date()));
            tdNtMembFoundChange.setMfchg_change_type(Constants.FundChangeType.wallet_out);//充值（进入余额：+）:1；消费（余额支出：-）:2
            tdNtMembFoundChange.setMfchg_change_name(Constants.ChargeReason.buy_weike_msg);
            tdNtMembFoundChange.setType(Constants.ChargeReason.buy_weike_code);
            tdNtMembFoundChange.setMoney_change_type(payChannel);//
            tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChange);
        }
        // Ping++ notify 先返回，该订单的记录已插入数据库，更新业务字段
        else {
            //补全第三方支付的订单信息
            tdNtMembFoundChange.setMemb_id(memb_id);
            tdNtMembFoundChange.setMfchg_change_month(DateUtil.getMonth(new Date()));
            tdNtMembFoundChange.setMfchg_change_type(Constants.FundChangeType.wallet_out);//1充值（进入余额：+）；2消费（余额支出：-）
            tdNtMembFoundChange.setMfchg_change_name(Constants.ChargeReason.buy_weike_msg);
            tdNtMembFoundChange.setType(Constants.ChargeReason.buy_weike_code);
            tdNtMembFoundChange.setMoney_change_type(payChannel);//支付渠道
            logger.info("Ping++ notify 先返回，该订单的记录已插入数据库，更新业务字段");
            tdNtMembFoundChangeDao.updatePaymentInfo(tdNtMembFoundChange);
        }
    }


    /**
     * 创建订单
     *
     * @param req
     * @param memb_id
     * @param ip
     */
    public Map<String, Object> studentCreateOrder(StudentCreateOrderRequest req, Integer memb_id, String ip) throws ClientException {
        Map<String, Object> map = new HashMap<>();
        logger.info("pingAppId:" + pingAppId + ", pingSecretKey:" + pingSecretKey + ", pingTest:" + pingTest);
        try {
            Weike weike = weikeDao.getById(req.getWeike_id());
            if (weike == null) {
                throw new ClientException("微课不存在，weike_id:" + req.getWeike_id());
            }

            BigDecimal money = weike.getStudent_price();
            logger.info("=========== is test ==========="+"yes".equals(pingTest));
            //测试环境，支付金额为0.01
            if ("yes".equals(pingTest)) {
                money = new BigDecimal(0.01);
                logger.info("money="+money.floatValue());
            }

            Pingpp.apiKey = this.pingSecretKey;
            Map<String, Object> chargeParams = new HashMap<String, Object>();
            chargeParams.put("order_no", OrderUtil.getOrderNumber());
            chargeParams.put("amount", money.multiply(new BigDecimal(100)).longValue());  //单位为分
            Map<String, String> app = new HashMap<String, String>();
            app.put("id", this.pingAppId);
            chargeParams.put("app", app);
            chargeParams.put("channel", req.getChannel());  //微信wx
            chargeParams.put("currency", "cny");
            chargeParams.put("client_ip", ip);
            chargeParams.put("subject", "微课购买");
            chargeParams.put("body", "微课购买");
            Charge charge = Charge.create(chargeParams);

            map = new HashMap<>();
            map.put("charge", charge);
        } catch (AuthenticationException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException("支付接口调用失败");
        } catch (InvalidRequestException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException("支付接口调用失败");
        } catch (APIConnectionException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException("支付接口连接失败");
        } catch (APIException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException("支付接口连接失败");
        } catch (ChannelException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException("支付方式错误");
        }
        return map;
    }

    /**
     * 查询最热直播课 （只查询3条数据，用于发现-首页-最热公开课）
     */
    public List<WeikeBoutiqueListDto> hotWeikeTop3(Integer memb_id) {
        RowBounds rowBounds = new RowBounds(0, 3);
        List<WeikeBoutiqueListDto> list = weikeDao.searchWeikeHotList(rowBounds);
        List<WeikeStudentBuy> weikeStudentBuyList = new ArrayList<>();
        if (list == null) {
            list = new ArrayList<>();
        }
        if(memb_id != 0 && memb_id != null) {
            WeikeSubscription weikeSubscription = weikeSubscriptionDao.findValidSubscribedByMembId(memb_id);
            for (WeikeBoutiqueListDto weikeBoutiqueListDto : list) {
                WeikeStudentBuy weikeStudentBuy = new WeikeStudentBuy();
                weikeStudentBuy.setWeike_id(weikeBoutiqueListDto.getId());
                weikeStudentBuy.setMemb_id(memb_id);
                weikeStudentBuyList = weikeStudentBuyDao.find(weikeStudentBuy);
                if(weikeSubscription != null){
                    weikeBoutiqueListDto.setIs_lock(0);
                }
                if (weikeStudentBuyList.size() > 0) {
                    weikeBoutiqueListDto.setIs_lock(0);
                }
            }
        }
        return list;
    }

    /**
     * 查询最热直播课 （只查询3条数据，用于发现-首页-最热公开课）
     */
/*
    public List<HotLiveDto> hotLiveTop3() {
        List<HotLiveDto> list = weikeDao.liveHot();
        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }
*/

    public MyWeikePageResponse studentMyWeike(PageRequest req, Integer memb_id) {
        MyWeikePageResponse pageResponse = new MyWeikePageResponse(req.getPageSize(), req.getCurrentPage());
        RowBounds rowBounds = new RowBounds(pageResponse.getOffset().intValue(), pageResponse.getPageSize().intValue());
        Long total = weikeDao.studentMyWeikeCount(memb_id);
        pageResponse.setTotal(total);
        List<StudentMyWeikeDto> list = weikeDao.studentMyWeike(memb_id, rowBounds);
        if (list == null) {
            list = new ArrayList<>();
        }
        pageResponse.setData(list);

        WeikeSubscription weikeSubscription = weikeSubscriptionDao.findValidSubscribedByMembId(memb_id);
        pageResponse.setWeikeSubscription(weikeSubscription);

        return pageResponse;
    }

    public PageResponse teacherFindComments(PageRequest req, Integer tea_id) {
        PageResponse pageResponse = new PageResponse(req.getPageSize(), req.getCurrentPage());
        RowBounds rowBounds = new RowBounds(pageResponse.getOffset().intValue(), pageResponse.getPageSize().intValue());
        Long total = weikeCommentsDao.teacherFindCommentsCount(tea_id);
        pageResponse.setTotal(total);
        List<TeacherFindCommentsDto> list = weikeCommentsDao.teacherFindComments(tea_id, rowBounds);
        if (list == null) {
            list = new ArrayList<>();
        }
        pageResponse.setData(list);

        return pageResponse;
    }

    public void teacherReplyComments(TeacherReplyCommentRequest req, Integer tea_id) {
        WeikeComments comments = new WeikeComments();
        comments.setTea_id(tea_id);
        comments.setReply(req.getReplyContent());
        comments.setId(req.getCommentsId());
        comments.setUpdate_user(tea_id);
        comments.setUpdate_date(new Date());
        weikeCommentsDao.update(comments);
    }

    /**
     * 查询学生是否购买过课程（购买课程后才能给老师发私信。因为有其他机构到我们app中，通过给发老师私信挖外教老师。）
     * <p>
     * 购买过微课和课程的都算，购买直播课不算
     *
     * @param memb_id
     * @return
     */
    public StudentIsPurchasedDto studentIsPurchased(Integer memb_id) {
        StudentIsPurchasedDto studentIsPurchasedDto = new StudentIsPurchasedDto();
        WeikeStudentBuy pojo = new WeikeStudentBuy();
        pojo.setMemb_id(memb_id);
        pojo.setPayment_status(Integer.parseInt(Constants.PayState.success));
        List<WeikeStudentBuy> weikeStudentBuyList = weikeStudentBuyDao.find(pojo);
        List<WeikeSubscription> subscriptionsWeikeList = weikeSubscriptionDao.findAllByMembId(memb_id);

        if (weikeStudentBuyList != null && weikeStudentBuyList.size() > 0) {
            studentIsPurchasedDto.setIsPurchased(StudentIsPurchasedDto.Yes);//购买过
            logger.info("学生（memb_id=" + memb_id + "）购买过微课");
        } else if (subscriptionsWeikeList != null && subscriptionsWeikeList.size() > 0) {
            studentIsPurchasedDto.setIsPurchased(StudentIsPurchasedDto.Yes);//购买过
            logger.info("学生（memb_id=" + memb_id + "）购买过VIP");
        } else {
            Long n = weikeStudentBuyDao.findStudentBuyCourseCount(memb_id);//查询学生购买的课程数量
            if (n != null && n > 0) {
                studentIsPurchasedDto.setIsPurchased(StudentIsPurchasedDto.Yes);//购买过
                logger.info("学生（memb_id=" + memb_id + "）购买过课程");
            }
        }

        return studentIsPurchasedDto;
    }

    public void audioPlayStatusReceive(AudioPlayStatusReceiveDto req, Integer memb_id) {
        WeikeStudentPlayedAudio pojo = new WeikeStudentPlayedAudio();
        pojo.setWeike_id(req.getWeike_id());
        pojo.setWeike_content_id(req.getWeike_content_id());
        pojo.setMemb_id(memb_id);


        WeikeStudentPlayedAudio playedAudio = weikeStudentPlayedAudioDao.search(pojo);

        // 1. 记录播放的哪条语音
        if (playedAudio != null) {
            playedAudio.setPlay_number(playedAudio.getPlay_number() + 1);
            playedAudio.setLast_play_date(new Date());
            weikeStudentPlayedAudioDao.update(playedAudio);
        } else {
            playedAudio = new WeikeStudentPlayedAudio();
            playedAudio.setPlay_number(1);
            Date date = new Date();
            playedAudio.setFirst_play_date(date);
            playedAudio.setLast_play_date(date);
            playedAudio.setWeike_id(req.getWeike_id());
            playedAudio.setWeike_content_id(req.getWeike_content_id());
            playedAudio.setMemb_id(memb_id);
            weikeStudentPlayedAudioDao.insert(playedAudio);
        }

        // 2. 记录学习到哪一个章节
        WeikeContent weikeContent = weikeContentDao.findById(req.getWeike_content_id());
        WeikePart part = weikePartDao.findByWeikeIdAndSort(weikeContent.getWeike_id(), weikeContent.getWeike_part_sort());

        WeikeStudentStudyPart studyPartPojo = new WeikeStudentStudyPart();
        studyPartPojo.setMemb_id(memb_id);
        studyPartPojo.setWeike_id(req.getWeike_id());
        studyPartPojo.setWeike_part_id(part.getId());
        WeikeStudentStudyPart studyPart = weikeStudentStudyPartDao.search(studyPartPojo);
        if (studyPart != null) {
            studyPart.setPlay_number(studyPart.getPlay_number() + 1);
            studyPart.setLast_play_date(new Date());
            weikeStudentStudyPartDao.update(studyPart);
        } else {
            studyPartPojo.setPlay_number(1);
            Date now = new Date();
            studyPartPojo.setFirst_play_date(now);
            studyPartPojo.setLast_play_date(now);
            weikeStudentStudyPartDao.insert(studyPartPojo);
        }

    }

    //获取前十节微课的内容
    public PageResponse getWeikeTop10(Integer memb_id) {
        StudentFindAllCoursePageRequest req = new StudentFindAllCoursePageRequest();
        PageResponse responseData = this.getAllCourse(req,memb_id);
        return responseData;
    }

    //获取全部课程信息
    public PageResponse getAllCourse(StudentFindAllCoursePageRequest req,Integer memb_id) {
        PageResponse pageResponse = new PageResponse(req.getPageSize(), req.getCurrentPage());
        List<CompositeWeike> result = new ArrayList<CompositeWeike>();
        RowBounds row = new RowBounds(pageResponse.getOffset().intValue(), pageResponse.getPageSize().intValue());
        Weike pojo = new Weike();
        pojo.setDeleted(0);
        pojo.setPublished(1);
        pojo.setShow_on_student(1);
        if (req.getCategory_id() != null && req.getCategory_id().intValue() != 0) {
            pojo.setCategory_id(req.getCategory_id());
        }
        Long total = weikeDao.searchWeikeCount(pojo);

        List<Weike> weikeList = weikeDao.searchWeike(pojo, row);
        List<Integer> teaIds = new ArrayList<Integer>();
        for (Weike weike : weikeList) {
            CompositeWeike com = new CompositeWeike();
            List<WeikeStudentBuy> weikeStudentBuyList = new ArrayList<>();
            if(memb_id != 0 && memb_id != null){
                WeikeSubscription weikeSubscription = weikeSubscriptionDao.findValidSubscribedByMembId(memb_id);
                WeikeStudentBuy weikeStudentBuy=new WeikeStudentBuy();
                weikeStudentBuy.setMemb_id(memb_id);
                weikeStudentBuy.setWeike_id(weike.getId());
                weikeStudentBuyList = weikeStudentBuyDao.find(weikeStudentBuy);
                if(weikeSubscription != null){
                    weike.setIs_lock(0);
                }
            }
            Integer count = weikeStudentBuyList.size();
            if(count > 0){
                weike.setIs_lock(0);
            }
            Teacher teacher = teacherDao.getById(weike.getPublish_user_id());
            com.setWeikeId(weike.getId());
            com.setCover_url_student(weike.getCover_url_student());
            com.setScore(weike.getScore());
            com.setTitle(weike.getTitle_student());
            com.setStudent_price(weike.getStudent_price());
            com.setBuy_number(weike.getBuy_number());

            com.setTea_id(teacher.getTea_id());
            com.setTea_head_portrait(teacher.getTea_head_portrait());
            com.setTeacher_name(teacher.getTea_name());
            com.setTeacher_valid(teacher.getTea_islock());

            com.setUpdate_lesson_count(weikePartDao.findUpdateLessonCount(weike.getId()));

            com.setFlag_name(dictDao.searchTagName(weike.getCategory_id()));

            com.setHot(weike.getHot());
            com.setIs_lock(weike.getIs_lock());
            teaIds.add(com.getTea_id());
            result.add(com);
        }
        pageResponse.setData(result);

        pageResponse.setTotal(total);
        return pageResponse;
    }

    // 关闭促销活动的显示：如果没有关闭过，插入一条数据；如果已关闭，不做任何操作。
    public void closeSalesPromotion(CloseSalesPromotionRequest closeSalesPromotionRequest, Integer memb_id) {
        MemberSalesPromotionSettings promotionSettings = memberSalesPromotionSettingsDao.findById(closeSalesPromotionRequest.getSalesPromotionId(), memb_id);
        if (promotionSettings == null) {
            promotionSettings = new MemberSalesPromotionSettings();
            promotionSettings.setClosed(Constants.SalesPromotionSettingsCloseStatus.YES);
            promotionSettings.setSalesPromotionId(closeSalesPromotionRequest.getSalesPromotionId());
            promotionSettings.setMemb_id(memb_id);
            memberSalesPromotionSettingsDao.insert(promotionSettings);
        }

    }

    /**
     * 今日精选 微课,只查询3条数据
     *
     * @return
     */
    public List<WeikeTodayBoutique> studentFindAllCourseForTodayBoutique(Integer memb_id) {
        //查询列表
        List<WeikeTodayBoutique> compositeCourseList = weikeDao.studentFindWeikeForTodayBoutique();
        List<WeikeStudentBuy> weikeStudentBuyList = new ArrayList<>();
        if(memb_id != 0 && memb_id != null){
            WeikeSubscription weikeSubscription = weikeSubscriptionDao.findValidSubscribedByMembId(memb_id);
            for(WeikeTodayBoutique weikeTodayBoutique : compositeCourseList){
                WeikeStudentBuy weikeStudentBuy = new WeikeStudentBuy();
                weikeStudentBuy.setWeike_id(weikeTodayBoutique.getId());
                weikeStudentBuy.setMemb_id(memb_id);
                weikeStudentBuyList = weikeStudentBuyDao.find(weikeStudentBuy);
                if(weikeSubscription != null){
                    weikeTodayBoutique.setIs_lock(0);
                }
                if(weikeStudentBuyList.size() > 0){
                    weikeTodayBoutique.setIs_lock(0);
                }
            }
        }

        //查询并设置老师的标签
        teacherLabels(compositeCourseList);

        return compositeCourseList;
    }

    /**
     * 查询并设置老师的标签和更新节数
     *
     * @param compositeCourseList
     */
    private void teacherLabels(List<WeikeTodayBoutique> compositeCourseList) {
        List<Integer> teaIds = new ArrayList<>();
        if (compositeCourseList != null && compositeCourseList.size() > 0) {

            for (WeikeTodayBoutique cc : compositeCourseList) {
                teaIds.add(cc.getTea_id());
            }
            logger.info("查询并设置老师的标签");
            List<TeacherLabel> teaLabels = compositeCourseDao.getTeachersLabels(teaIds);

            if (teaLabels != null) {
                for (WeikeTodayBoutique cc : compositeCourseList) {
                    for (TeacherLabel label : teaLabels) {
                        if (label.getTea_id().intValue() == cc.getTea_id().intValue()) {
                            cc.getTeacher_tags().add(label.getLab_cn_name());
                        }
                    }
                }
            } else {
                logger.info("teaLabels is null,不设置老师标签,teaIds:" + teaIds);
            }
            for (WeikeTodayBoutique cc : compositeCourseList) {
                Integer updateCount = weikePartDao.findUpdateLessonCount(cc.getId());
                TdNtTeacherResult teacher = tdNtTeacherDao.getById(cc.getTea_id());
                cc.setUpdate_lesson_count(updateCount);
                cc.setTeacher_name(teacher.getTea_name());
                cc.setTeacher_valid(teacher.getTea_label() + "");
                cc.setTeacher_avatar_url(teacher.getTea_head_portrait());
            }
        }
    }

    /**
     * 发布微课
     *
     * @param weike_id
     * @param update_user
     * @return
     */
    @Transactional
    public void uploadWeike(String weike_id, Integer update_user) {
        weikeContentDao.updatePublish(Long.valueOf(weike_id), update_user);
        weikePartDao.updatePublish(Long.valueOf(weike_id), update_user);
        weikeImageDao.updatePublish(Long.valueOf(weike_id), update_user);

        // 给老师计算提成
        chargeForTeacher(weike_id, update_user);
    }

    //判断微课的已提成语音总时长CD是否大于10小时：If(CD>10) { 1.停止按小时计费；2.每个购买记录提成5美元 }。
    // if(CD<=10)
    private void chargeForTeacher(String weike_id, Integer teacherId) {
        // 查询微课的已提成语音总时长CD(chargeDuration)(小时)
        Integer chargeDuration = weikeTeacherHourChargeDao.findChargeTotalDuration(Long.valueOf(weike_id));
        if (chargeDuration >= 10) {
            logger.info("老师微课提成，已提成时长chargeDuration:" + chargeDuration + " >= 10,不符合按照时长提成规则。发布微课不计费。weike_id=" + weike_id);
            return;
        }
        // 查询微课实际的语音总时长(小时)
        Integer totalDuration = weikeDao.findTotalDurationById(weike_id);

        // 可计费小时数（超过10小时不计费）：chargableDuration = 10 - (totalDuration - chargeDuration)+chargeDuration
        Integer chargableDuration = 10 - chargeDuration;

        // 本次新增未计费的语音小时数
        Integer n = totalDuration - chargeDuration;

        // 本次应该计费的小时数
        Integer shouldChargeNum = 0;
        if (chargableDuration > n) {
            shouldChargeNum = n;
        } else {
            shouldChargeNum = shouldChargeNum;
        }
        logger.info("\n              可计费小时数:" + chargableDuration + "\n   本次新增未计费的语音小时数:" + n + "\n        本次应该计费的小时数:" + shouldChargeNum);

        if (shouldChargeNum <= 0) {
            logger.info("本次应该计费的小时数小于=0 ，发布微课不计费。weike_id=" + weike_id);
            return;
        }

        // 计费
        //1. 保存微课小时计费记录
        WeikeTeacherHourCharge pojo = new WeikeTeacherHourCharge();
        pojo.setAudio_total_duration(totalDuration);
        pojo.setCharge_hour(shouldChargeNum);
        pojo.setWeike_id(Long.parseLong(weike_id));
        weikeTeacherHourChargeDao.insert(pojo);

        // 2. 添加老师账单
        BigDecimal balance = tdNtTeacherDao.findTdNtTeacherBalance(teacherId);   // 查询老师账户余额（)
        TdNtTeaFoundChange teaFoundChange = new TdNtTeaFoundChange();
        teaFoundChange.setTea_id(teacherId);
        teaFoundChange.setState(Constants.PayState.success);
        teaFoundChange.setTfchg_front_amount(balance);
        BigDecimal earned = new BigDecimal(shouldChargeNum * 20);  //20美元/小时
        teaFoundChange.setTfchg_back_amount(balance.add(earned));  //设置变化后的金额
        teaFoundChange.setTfchg_change_amount(earned);
        Date now = new Date();
        Timestamp now2 = new Timestamp(now.getTime());
        teaFoundChange.setTfchg_change_month(DateUtil.getMonth(now));
        teaFoundChange.setTfchg_change_time(now2);
        teaFoundChange.setTfchg_change_type(Constants.FundFlowType.in);//
        teaFoundChange.setTfchg_account(new BigDecimal(0.00d));//老师提现时使用
        teaFoundChange.setTfchg_counter_fee(new BigDecimal(0.00d));//老师提现时使用
        teaFoundChange.setTfchg_number(OrderUtil.getOrderNumber());//订单号
        teaFoundChange.setType(Constants.fundChangeTypeForTeacher.weike_code);
        teaFoundChange.setTfchg_change_name(Constants.fundChangeTypeForTeacher.weike_msg);
        tdNtTeaFoundChangeDao.insert(teaFoundChange);

        ///3. 更新老师余额
        tdNtTeacherDao.addBalance(teacherId, earned);
        logger.info(" ---------- 计费 end -----------");

    }

    /**
     * 审核微课
     *
     * @param weike_id
     * @param update_user
     * @return
     */
    public void teacherSubmitWeike(String weike_id, Integer update_user) {

        Weike weike = new Weike();
        weike.setId(Long.valueOf(weike_id));
        weike.setUpdate_user(update_user);
        //查看微课发布状态
        Integer published=weikeDao.selectAllById(weike.getId()).getPublished();
        if(published==1){
            uploadWeike(weike_id,update_user);
        }else{
            //微课未发布，微课提交审核
            weike.setApproved(0);
            weikeDao.update(weike);
        }

    }

    public String uploadTeaIntro(MultipartFile file, Integer teaId) {

        try {
            //上传视频到OSS
            String oname = file.getOriginalFilename();
            String newName = AliyunOssUtil.getRandomFileName(oname);
            String key = WAIJIAOJUN_Teacher + teaId + "/introVideo/" + newName;
            AliyunOssUtil.upload(key, file.getInputStream(), file.getSize());

            tdNtTeacherDao.addVideo(teaId, key);
            return key;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServerException();
        }
    }

    public String uploadTeaIntroCover(MultipartFile tea_video_intro_cover, Integer tea_id) {
        try {
            //上传视频封面到OSS
            String oname = tea_video_intro_cover.getOriginalFilename();
            String newName = AliyunOssUtil.getRandomFileName(oname);
            String key = WAIJIAOJUN_Teacher + tea_id + "/introVideo/" + newName;
            AliyunOssUtil.upload(key, tea_video_intro_cover.getInputStream(), tea_video_intro_cover.getSize());
            tdNtTeacherDao.addVideoCover(tea_id, key);
            return key;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServerException();
        }
    }

    public Double findWeikeVipPrice() {
        // 年度会员价格
        SystemConfig systemCourseVipPriceForYear = systemConfigDao.findByCode("systemCourseVipPriceForYear");
        Double price = Double.parseDouble(systemCourseVipPriceForYear.getValue());
        return price;
    }

    public List<WeikeContent> getWeikeAudio(Long weikeId) {
        List<WeikeContent> weikeContents = weikeContentDao.searchByWeikeIdForTeacher(weikeId);
        Iterator<WeikeContent> iterator = weikeContents.iterator();
        while(iterator.hasNext()){
            WeikeContent wctx = iterator.next();
            if(!wctx.getType().equalsIgnoreCase("audio") || wctx.getContent().endsWith(".mp3")){
                iterator.remove();
            }

        }
        return weikeContents;
    }

    @Transactional
    public Integer studentBuyWeike(Integer memb_id,Integer weike_id) {
        WeikeStudentBuy weikeStudentBuy = new WeikeStudentBuy();
        Date now = new Date();
        weikeStudentBuy.setMemb_id(memb_id);
        weikeStudentBuy.setWeike_id(Long.valueOf(weike_id));
        weikeStudentBuy.setIs_vip_view(0);
        weikeStudentBuy.setPayment_status(2);
        weikeStudentBuy.setCreate_user(memb_id);
        weikeStudentBuy.setCreate_date(now);
        weikeStudentBuy.setUpdate_user(memb_id);
        weikeStudentBuy.setDeleted(0);
        weikeStudentBuy.setStudy_number((long) 0);
        weikeStudentBuy.setUpdate_date(now);
        Integer count = weikeStudentBuyDao.insertSelective(weikeStudentBuy);
        weikeDao.updateBuyNumber(Long.valueOf(weike_id));
        return count;
    }

    public WeikeVipUrl getVipUrl(){
        WeikeVipUrl weikeVipUrl = new WeikeVipUrl();
        weikeVipUrl.setVip_link_url(websiteConfigDao.getData(30));
        weikeVipUrl.setVip_url(websiteConfigDao.getData(34));
        return weikeVipUrl;
    }
}
